// Armisael.cpp : Defines the entry point for the console application.
//

// OpenCV_Helloworld.cpp : Defines the entry point for the console application.
// Created for build/install tutorial, Microsoft Visual C++ 2010 Express and OpenCV 2.1.0

#include "stdafx.h"

#include <cv.h>
#include <cxcore.h>
#include <highgui.h>

#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
        IplImage *img = cvLoadImage("nozzle.jpg");
        cvNamedWindow("Image:",1);
        cvShowImage("Image:",img);

	

		 //create a gray image by copying the original image
		 IplImage* gray = cvCreateImage(cvGetSize(img), 8, 1);
 
		 //create storage device for hough circles
		 CvMemStorage* storage = cvCreateMemStorage(0);
 
		 //convert the gray image to grayscale
		 cvCvtColor( img, gray, CV_BGR2GRAY );
 
		 //smooth the gray image down. it takes in the gray image and outputs the gray image
		 cvSmooth( gray, gray, CV_GAUSSIAN, 9, 9, 0, 0 );

		 cvNamedWindow("Image2:",1);
	     cvShowImage("Image2:",gray);

		 //detect edges of the image by performing the canny operator
		cvCanny(gray, gray, 0, 20, 3);
 
		 //run the hough transform and store the coordinates/radius of the circles in the circles object. it stores
		 //it int a 3 column matrix with x, y, and radius as the columns
		 CvSeq* circles = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, gray->height/4, 100, 100, 0, 1000);

		 //grab the total number of circles found
		 int total = circles->total;

		 cout << "total circles= " << total <<endl;
			 
		//cycle through the circle matrix and print out circles detected onto the original image
		 for (int i = 0; i < total; i++)
		 {
		  //grab a row of the circle matrix
		  float* p = (float*)cvGetSeqElem( circles, i );
		  //it prints the circle using the p[0]/x, p[1]/y, and p[2], as the radius
		  cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(120,120,120), 1, 8, 1 );
		 }
		

		 //create the windows to display the images
		cvNamedWindow( "circles", 1 ); cvNamedWindow("gray", 1);

			 //show the images in the correct windows
			 cvShowImage("gray", gray);
			 cvShowImage( "circles", img );
 
		 //wait for the user to press anything
		 cvWaitKey(0);
 
		 //release camera, images, and windows
		 //cvReleaseCapture(&capture); 
		 cvReleaseImage(&gray); cvReleaseImage(&img); cvDestroyWindow("circles"); cvDestroyWindow("gray");

	

        cvWaitKey();
        cvDestroyWindow("Image:");
        cvReleaseImage(&img);

        return 0;
}